import { http } from '@/utils/http'
import { userStore } from '@/stores'


// 前端拼接 OpenUrl
const getOpenUrl = (result) => {
  let openUrl = getApp().globalData.requestUrl + `/uploadFile/image/${result.fileIdStr}`
  // 兼容 h5
  // #ifdef H5
  openUrl = openUrl.replace('/api', '')
  // #endif
  let fileExt = result.fileName.replace(/.+\./, "").toLowerCase();
  if (fileExt) openUrl += '.' + fileExt

  return packagedSetUrlQuery(openUrl)
}
// 拼接参数
const packagedSetUrlQuery = (openUrl) => {
  openUrl += openUrl.indexOf('?') >= 0 ? '&' : '?'
  const userInfoStore = userStore()
  const token = userInfoStore.profile?.ticket

  openUrl += 'ticket=' + token
  openUrl += '&service-code=H5'

  return openUrl
}

// 处理 result
const handleResult = (result) => {
  let openUrl = result.openUrl
  // openUrl
  if (!openUrl) {
    openUrl = getOpenUrl(result)
  } else {
    // 拼接查询参数
    openUrl = packagedSetUrlQuery(openUrl)
  }

  result.openUrl = openUrl
}
// 处理 getFileInfo 接口的返回值
const packagedGetFileInfoResult = (res) => {
  // 对结果进行处理
  if (res.code == 200) {
    const result = res.result
    if (result) {
      // 数组 多文件
      if (Array.isArray(result)) {
        result.forEach((item) => {
          handleResult(item)
        })
      }
      // 对象 单文件
      else {
        handleResult(result)
      }
    }
  }
}
/**
 * 获取图片信息
 */
const packagedGetFileInfo = (param) => {
  return new Promise((resolve, reject) => {
    let api = '/uploadFile/getFileInfo'
    if (param.hasOwnProperty('idList')) {
      api = '/uploadFile/getFileInfoList'
    }
    http({
      method: 'POST',
      url: api,
      data: param,
    }).then((res) => {
      packagedGetFileInfoResult(res)
      resolve(res)
    }).catch((err) => {
      reject(err)
    })
  })
}

/**
 * 上传文件
 */
const packagedUploadFile = (option) => {
  return uni.uploadFile({
    // #ifdef APP-PLUS
    url: getApp().globalData.requestUrl + '/uploadFile/commonUpload',
    // #endif
    // #ifdef H5
    url: '/uploadFile/commonUpload',
    // #endif
    name: 'files',
    header: {
      'service-code': 'H5',
      ticket: uni.getStorageSync('userInfo').token,
    },
    ...option,
    success: (res) => {
      // 处理结果
      if (res.statusCode == 200) {
        res.data = JSON.parse(res.data)
        if (res.data) {
          const result = res.data.result
          const file = result[0]
          // 手动设置 openUrl
          if (!file.openUrl) {
            file.openUrl = getOpenUrl(file)
          }
        }
        res.data = JSON.stringify(res.data)
      }
      option.success(res)
    },
  })
}

export {
  getOpenUrl,
  packagedGetFileInfo,
  packagedSetUrlQuery,
  packagedUploadFile,
  packagedGetFileInfoResult,
}
